package com.example.mymvvmdemo.models.login;


import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CompoundButton;

import androidx.lifecycle.ViewModelProvider;

import com.example.mymvvmdemo.MyApplication;
import com.example.mymvvmdemo.R;
import com.example.mymvvmdemo.base.BaseLoadActivity;
import com.example.mymvvmdemo.constants.Constants;
import com.example.mymvvmdemo.constants.UrlConstants;
import com.example.mymvvmdemo.constants.UrlTypeConstants;
import com.example.mymvvmdemo.databinding.ActivityLoginBinding;
import com.example.mymvvmdemo.dialog.LoadingAnimDialog;
import com.example.mymvvmdemo.entity.FailEntity;
import com.example.mymvvmdemo.models.login.dialog.ReadAgreementDialog;
import com.example.mymvvmdemo.models.login.entity.LoginEntity;
import com.example.mymvvmdemo.net.presenter.PostBodyPresenter;
import com.example.mymvvmdemo.net.view.IView;
import com.example.mymvvmdemo.utils.LogUtils;
import com.example.mymvvmdemo.utils.SpUtils;
import com.example.mymvvmdemo.utils.StrUtils;
import com.example.mymvvmdemo.utils.TextColorUtils;
import com.example.mymvvmdemo.utils.ToastUtils;

import java.util.HashMap;

public class LoginActivity extends BaseLoadActivity<ActivityLoginBinding> implements View.OnClickListener, IView.PostBodyView {

    private LoginViewModel viewModel;
    private PostBodyPresenter postBodyPresenter;
    private ReadAgreementDialog readAgreementDialog;

    /*** 加载时候的Dialog */
    private LoadingAnimDialog loadingDialog;

    @Override
    protected void showDialog() {
        if (loadingDialog == null)
            loadingDialog = new LoadingAnimDialog(this, getResources().getString(R.string.load));
        if (!loadingDialog.isShowing()) loadingDialog.show(this);
    }

    @Override
    protected void dismissDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.close(this);
        }
    }

    @Override
    protected void initData() {

        viewModel = new ViewModelProvider(this).get(LoginViewModel.class);
        postBodyPresenter = new PostBodyPresenter(this);
        initTextColor();


    }

    @Override
    protected void initListener() {
        binding.ivRead.setOnClickListener(this);
        binding.ivRemember.setOnClickListener(this);
        binding.tvRegister.setOnClickListener(this);
        binding.tvForgot.setOnClickListener(this);
        binding.tvLogin.setOnClickListener(this);
        binding.ivClearName.setOnClickListener(this);
        binding.ivClearPassword.setOnClickListener(this);
        binding.cbPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    binding.etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    binding.etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                }
                Selection.setSelection(binding.etPassword.getText(), binding.etPassword.getText().length());
            }
        });

        binding.etAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                binding.ivClearName.setVisibility(charSequence.toString().length() > 0
                        ? View.VISIBLE : View.GONE);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        binding.etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                binding.ivClearPassword.setVisibility(s.toString().length() > 0
                        ? View.VISIBLE : View.GONE);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_remember:
                changeRememberState();
                break;
            case R.id.iv_read:
                changeReadState();
                break;
            case R.id.tv_register:
                viewModel.startRegisterActivity(this);
                break;
            case R.id.tv_forgot:
                viewModel.startForgetActivity(this);
                break;
            case R.id.tv_login:
                login();
                break;
            case R.id.iv_clear_name:
                binding.etAccount.setText("");
                break;
            case R.id.iv_clear_password:
                binding.etPassword.setText("");
                break;
            default:
                break;
        }
    }

    @Override
    public void initDialog() {
        super.initDialog();

        readAgreementDialog = new ReadAgreementDialog(this);
        readAgreementDialog.setListener(new ReadAgreementDialog.PromptClickListener() {
            @Override
            public void onUserClick() {
                toast("用户协议", ToastUtils.TOA_W);
            }

            @Override
            public void onPrivateClick() {
                toast("隐私协议", ToastUtils.TOA_W);
            }

            @Override
            public void onCancelClick() {

            }

            @Override
            public void onConfirmClick() {
                changeReadState();
                login();
            }
        });

    }

    /************************************自定义方法**************************************/
    private void login() {

        String account = binding.etAccount.getText().toString();
        String password = binding.etPassword.getText().toString();

        if (StrUtils.isEmpty(account)) {
            toast(R.string.input_account, ToastUtils.TOA_S);
            return;
        }
        if (StrUtils.isEmpty(password)) {
            toast(R.string.input_password, ToastUtils.TOA_S);
            return;
        }
        if (!viewModel.isRead) {
            if (readAgreementDialog != null) {
                readAgreementDialog.show();
            }
            return;
        }

        viewModel.saveUserAccount(account, viewModel.isRememberAccount ? password : "");

        startLoadLogin();

    }

    private void initShowView() {
        String account = SpUtils.getSpUtils(MyApplication.getInstance(), Constants.ACCOUNT_NAME)
                .getStringValue(Constants.USER_ACCOUNT, null);
        String password = SpUtils.getSpUtils(MyApplication.getInstance(), Constants.ACCOUNT_NAME)
                .getStringValue(Constants.USER_PASSWORD, null);

        if (!StrUtils.isEmpty(account)) {
            binding.etAccount.setText(account);
        }
        if (!StrUtils.isEmpty(password)) {
            binding.etPassword.setText(password);
            viewModel.isRememberAccount = true;
            binding.ivRemember.setImageResource(R.drawable.ic_svg_select_green);
        }


    }

    private void startLoadLogin() {
        showDialog();

        String account = binding.etAccount.getText().toString();
        String password = binding.etPassword.getText().toString();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("account", account);
        hashMap.put("password", password);
        postBodyPresenter.startLoadPostBody(UrlConstants.login, hashMap, UrlTypeConstants.login);
    }

    private void changeRememberState() {
        viewModel.isRememberAccount = !viewModel.isRememberAccount;
        binding.ivRemember.setImageResource(viewModel.isRememberAccount ?
                R.drawable.ic_svg_select_green :
                R.drawable.ic_svg_no_select_green);

    }

    private void changeReadState() {
        viewModel.isRead = !viewModel.isRead;
        binding.ivRead.setImageResource(viewModel.isRead ?
                R.drawable.ic_svg_select_green :
                R.drawable.ic_svg_no_select_green);

    }


    private void initTextColor() {

        TextColorUtils.initText(this, binding.tvRegister,
                getString(R.string.login_no_register),
                getString(R.string.login_register),
                "",
                getResources().getColor(R.color.green_one), R.color.white,
                new TextColorUtils.TextColorListener() {
                    @Override
                    public void onLeftClick() {

                    }

                    @Override
                    public void onRightClick() {

                    }
                }
        );

        TextColorUtils.initText(this, binding.tvRead,
                getString(R.string.login_read_all),
                getString(R.string.login_user),
                getString(R.string.login_private),
                getResources().getColor(R.color.green_one), R.color.white,
                new TextColorUtils.TextColorListener() {
                    @Override
                    public void onLeftClick() {
                        toast("用户协议", ToastUtils.TOA_S);
                    }

                    @Override
                    public void onRightClick() {
                        toast("隐私协议", ToastUtils.TOA_S);
                    }
                }
        );

    }


    /*************************************生命周期******************************************/
    @Override
    protected void onResume() {
        super.onResume();
        initShowView();
    }

    /*********************************数据请求回调************************************/
    @Override
    public void loadPostBodySuccess(String result, String type, int code) {
        if (type.equals(UrlTypeConstants.login)) {
            loadLoginSuccess(result, code);
        }
    }

    @Override
    public void loadPostBodyFail(String message, String type) {
        if (type.equals(UrlTypeConstants.login)) {
            loadLoginFail();
        }
    }

    @Override
    public void loadPostBodyAccountError(int code) {

    }

    @Override
    public void loadPostBodyNetWorkError(String type) {
        dismissDialog();
        toast(R.string.network_error, ToastUtils.TOA_W);
    }


    /*********************************处理请求后数据************************************/
    private void loadLoginSuccess(String result, int code) {

        dismissDialog();
        if (code != 200) {
            FailEntity registerFailEntity = gson.fromJson(result, FailEntity.class);
            String message = registerFailEntity.getData().getMessage().getMessages().get(0);
            toast(message, ToastUtils.TOA_W);
            return;
        }

        try {
            LoginEntity loginEntity = gson.fromJson(result, LoginEntity.class);
            String token = loginEntity.getData().getToken().getAccess();
            LogUtils.d("login token:" + token);
            MyApplication.setAuthToken(token);

            viewModel.startMainActivity(this);
        } catch (Exception e) {
            toast(R.string.app_error, ToastUtils.TOA_W);
        }


    }

    private void loadLoginFail() {
        dismissDialog();
        toast(R.string.login_fail, ToastUtils.TOA_W);
    }

}